import { Component } from "vue";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import type { Route, Meta } from '../type/router';

// 自动生成 routes
// 自动匹配view文件夹下的page.json和index.vue文件
// page.json为每段路由必须配置的文件,里面的数据为meta里的数据，可任意定义
// index.vue为实际的展示页面文件，如果存在子路由，则不必配置index.vue文件

export const routes:Array<Route> = [];


const context = import.meta.glob('../view/**/page.json', { eager: true, import: 'default' })
let pageUrl: Array<string> = Object.entries(context).map(([pagePath]) => {
  return pagePath.replace('./view', '')
})
let pageModules: Array<Meta> = Object.entries(context).map(([, config]) => {
  return config
}) as Array<Meta>


const vueContext = import.meta.glob('../view/**/index.vue', { eager: true, import: 'default' })
const vueRoute: Array<string> = Object.entries(vueContext).map(([pagePath]) => {
  return pagePath.replace('./view', '')
})
const vueModules: Array<Component> = Object.entries(vueContext).map(([, config]) => {
  return config
}) as Array<Component>

type Count = {
  count: number,
  index: number
}
let counts:Array<Count> = pageUrl.map((path,index) => {
  return {
    count: path.split('/').length - 1,
    index
  }
})
function toSorted(){
  return counts.sort((a, b) => a.count - b.count)
}
const sortedCounts = toSorted()
let sortedIndices = sortedCounts.map((item) => { return item.index })
function sortArrayByReferenceArray(array: any, referenceArray:Array<number>) {   
  let mappingArray = array.map((item: any, index: number) =>{
    return {  
      index,  
      value: item  
    }
  });  
  mappingArray.sort((a: any, b: any) => {  
    return referenceArray.indexOf(a.index) - referenceArray.indexOf(b.index);  
  });  
  let sortedIndices = mappingArray.map((item: any) => item.value);  
  return sortedIndices;  
}  
pageUrl = sortArrayByReferenceArray(pageUrl, sortedIndices)
pageModules = sortArrayByReferenceArray(pageModules, sortedIndices)

function findParentRoute(path: string, routes: Array<Route>): null | Route {
  for (const route of routes) {
    if (path.startsWith(route.path) && route.path != '/') {
      if(path.replace(route.path, '').split('/').length > 2){
        return findParentRoute(path.replace(route.path + '/', '') , route.children)
      } else {
        return route
      }
    }
  }
  return null;
}


pageModules.forEach((item, _index) => {
  const index = vueRoute.indexOf(pageUrl[_index].replace('/page.json', '') + '/index.vue')
  let path = pageUrl[_index].replace(".", "").replace("/page.json", "");
  const nameArr = path.split("/").filter((name) => !!name);
  const name = nameArr[nameArr.length - 1];
  path = path === "/home" ? "/" : path;
  const route: Route = {
    path,
    name,
    meta: item,
    children: [],
  };
  if(index !== -1) route.component = vueModules[index]
  const parentRoute = findParentRoute(path, routes);
  if (parentRoute) {
    const pathArr = route.path.split('/')
    route.path = pathArr[pathArr.length - 1]
    if(parentRoute.component) delete parentRoute.component
    parentRoute.children.push(route);
    if(!parentRoute.meta.redirect){
      console.error(`请在${parentRoute.name}文件夹的page.json里指定redirect重定向子路由`)
    } else {
      const redirectUrl = path.replace(name, '')
      parentRoute.redirect = redirectUrl + parentRoute.meta.redirect
    }
  } else {
    routes.push(route);
  }
});

console.log('routes', routes)

export default createRouter({
  history: createWebHistory(),
  routes: routes as unknown as readonly RouteRecordRaw[],
});
